package com.uchedao.vehicledetection.utils;

import com.nostra13.universalimageloader.utils.L;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * 
 * @author 叶晋
 * @修改时间 2013-3-8 下午5:49:27
 * 
 */
public class FileUpload {

	private String url;
	// private String fileName;
	// private File file;
	private UploadListener listener;// 下载监听接口
	// private String path;// 路径
	private InputStream is = null;
	private boolean cancel;// 取消

	public static final int STATE_NONE = 0;
	public static final int STATE_START = 1;
	public static final int STATE_CANCEL = 2;
	public static final int STATE_ERROR_FILE_NOT_FOUND = 3;
	public static final int STATE_ERROR_HTTP = 4;
	public static final int STATE_ERROR_OTHER = 5;
	public static final int STATE_SUCCESS = 6;

	private int state;

	private String responseMsg;

	private String errMsg;

	public String getErrMsg() {
		return errMsg;
	}

	public String getResponseMsg() {
		return responseMsg;
	}

	public int getState() {
		return state;
	}

	// public FileUpload() {
	// }

	public FileUpload(String uploadUrl) {
		url = uploadUrl;
	}

	/**
	 * 
	 * 
	 * @功能描述 结束
	 * 
	 * @author 叶晋
	 * @修改时间 2012-10-9 下午2:19:55
	 * 
	 */
	public void finish() {
		state = STATE_NONE;
		cancel = false;
		url = null;
		listener = null;
	}

	public boolean start(String filePath) {
		responseMsg = null;
		state = STATE_START;
		File file = new File(filePath);
		if (!file.exists()) {// 文件不存在
			state = STATE_ERROR_FILE_NOT_FOUND;

			errMsg = "文件不存在 :" + filePath;
			if (listener != null)
				listener.fileNoFoundError(filePath);

			return false;
		}
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			errMsg = "文件不存在 :" + filePath;
			state = STATE_ERROR_FILE_NOT_FOUND;
			if (listener != null)
				listener.fileNoFoundError(filePath);
			return false;
		}
		return start(is);
	}

	// public void start(String path, String fileName) {
	// state = STATE_START;
	// File file = new File(path, fileName);
	// String newFileName = file.getAbsolutePath();
	//
	// if (!file.exists()) {// 文件不存在
	// state = STATE_ERROR_FILE_NOT_FOUND;
	// if (listener != null)
	// listener.fileNoFoundError(newFileName);
	// return;
	// }
	// try {
	// is = new FileInputStream(file);
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// state = STATE_ERROR_FILE_NOT_FOUND;
	// if (listener != null)
	// listener.fileNoFoundError(newFileName);
	// return;
	// }
	// start(is);
	// }

	public boolean start(InputStream fis) {
		responseMsg = null;
		state = STATE_START;
		if (fis == null) {
			state = STATE_ERROR_OTHER;
			errMsg = "读取图片数据失败 ： inputStream is null";
			// throw new NullPointerException("inputStream is null");
			if (listener != null)
				listener.onError("读取图片数据失败 ： inputStream is null");
			return false;
		}
		HttpURLConnection http = null;
		OutputStream os = null;
		DataInputStream dis = null;
		int fileLen = -1;// 文件长度
		int uploadLen = 0;// 已上传长度
		try {
			fileLen = fis.available();
			L.i("url = " + url);
			http = (HttpURLConnection) new URL(url).openConnection();
			http.setRequestProperty("Content-Type", "application/octet-stream");// 设置contentType
			http.setRequestProperty("Content-Length", String.valueOf(fileLen));// 设置contentLength
			http.setRequestMethod("POST");
			http.setDoOutput(true);
			os = http.getOutputStream();
			byte[] buffer = new byte[10240];
			int len = -1;
			while ((len = fis.read(buffer)) != -1) {
				if (cancel) {
					state = STATE_CANCEL;
					if (listener != null) {
						listener.onCancel();
						return false;
					}
				}
				os.write(buffer, 0, len);
				os.flush();
				uploadLen += len;
				if (listener != null)
					listener.upload(uploadLen, fileLen);
			}

			http.connect();
			// 返回错误
			if (http.getResponseCode() < 200 || http.getResponseCode() >= 300) {
				state = STATE_ERROR_HTTP;
				errMsg = http.getResponseCode() + " : " + http.getResponseMessage();
				if (listener != null)
					listener.onHttpError(http.getResponseCode(), http.getResponseMessage());
				return false;
			}

			dis = new DataInputStream(http.getInputStream());
			byte[] data = new byte[dis.available()];
			dis.readFully(data);
			state = STATE_SUCCESS;
			responseMsg = new String(data, "UTF-8");
			if (listener != null)
				listener.onSuccess(new String(data));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			state = STATE_ERROR_OTHER;
			errMsg = e.getMessage();
			if (listener != null)
				listener.onError(e.getMessage());
		} catch (OutOfMemoryError e) {
			state = STATE_ERROR_OTHER;
			e.printStackTrace();
			errMsg = e.getMessage();
			if (listener != null)
				listener.onError(e.getMessage());
		} finally {

			try {
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			fis = null;
			try {
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			os = null;
			if (http != null)
				http.disconnect();
			http = null;
		}
		return false;
	}

	public UploadListener getListener() {
		return listener;
	}

	public void setListener(UploadListener listener) {
		this.listener = listener;
	}

	/**
	 * 取消
	 */
	public void cancel() {
		cancel = true;
	}

	/**
	 * 
	 * @功能描述 下载对话框监听接口
	 * 
	 * @author 叶晋
	 * @修改时间 2012-10-9 上午11:57:32
	 * 
	 */
	public interface UploadListener {
		/**
		 * 正在上传
		 * 
		 * @param uploadLen
		 *            已上传大小
		 * @param totalLen
		 *            总大小
		 */
		public void upload(int uploadLen, int totalLen);

		/**
		 * 
		 * @功能描述 上传完成
		 * 
		 * @author 叶晋
		 * @修改时间 2012-10-9 下午1:41:04
		 * 
		 */
		public void onSuccess(String str);

		/**
		 * 
		 * @功能描述 取消
		 * 
		 * @author 叶晋
		 * @修改时间 2012-10-9 上午11:59:03
		 * 
		 */
		public void onCancel();

		/**
		 * 
		 * @功能描述 文件不存在错误
		 * 
		 * @author 叶晋
		 * @修改时间 2012-10-9 上午11:59:18
		 * 
		 */
		public void fileNoFoundError(String path);

		/**
		 * 
		 * @功能描述 网络错误
		 * 
		 * @author 叶晋
		 * @修改时间 2012-10-9 下午12:00:06
		 * 
		 * @param responseCode
		 * @param msg
		 */
		public void onHttpError(int responseCode, String msg);

		/**
		 * 
		 * @功能描述 其他错误
		 * 
		 * @author 叶晋
		 * @修改时间 2012-10-9 下午12:00:36
		 * 
		 * @param msg
		 */
		public void onError(String msg);
	}

}
